package com.springbootmybatisplusenum.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Classname MyMetaObjectHandler
 * @Description TODO Mybatis-Plus自动填充功能
 * @Date 2022/5/31 15:40
 * @Created chenjian
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入数据时填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 先获取到version的值，再进行判断，如果为空，就进行填充，如果不为空，就不做处理
        Object version = getFieldValByName("version", metaObject);
        if (null == version) {
            setFieldValByName("version", 1, metaObject);
        }
        Object createTime = getFieldValByName("create_time",metaObject);
        if (null == createTime){
            setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        }
    }

    /**
     * 更新数据时填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        Object updateTime = getFieldValByName("update_time",metaObject);
        if (null == updateTime){
            setFieldValByName("updateTime", LocalDateTime.now(),metaObject);
        }
    }

}

